package com.mission.shaco.warehouse

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.mission.shaco.warehouse.models.Grids
import com.mission.shaco.warehouse.stockout.MultiActivity
import kotlinx.android.synthetic.main.activity_grid_barcode.*
import java.lang.Integer.parseInt
import android.view.KeyEvent
import com.androidquery.AQuery
import com.androidquery.callback.AjaxCallback
import com.androidquery.callback.AjaxStatus
import com.mission.shaco.warehouse.models.ClientConfig
import com.mission.shaco.warehouse.models.Grids.*
import org.json.JSONObject


class GridBarcodeActivity : ScannerActivity() {
    var currentIndex:Int = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_grid_barcode)
        val extras = getIntent().extras
        var total = extras.getInt("total")
        currentIndex = 1
        for (i in 1..Grids.gridNumber ) {
            gridJson.put(i.toString(),"")
        }
        saveGrids()

        initSet()
    }

    fun initSet(){
        txtGridTotal.setText("总共 "+ Grids.gridNumber.toString()+"格" )
        btnPrev.setOnClickListener(this)
        btnNext.setOnClickListener(this)
        btnClose.setOnClickListener(this)
        btnComplete.setOnClickListener(this)
        reloadBarcodeResult()
    }

    var checkGridThread: Runnable = Runnable {
        try {
            val aq: AQuery = AQuery(this)
            val params = HashMap<String, Any>()

            var map = JSONObject()
            map.put("grid_number",code)
            params.put("datas", map)
            var jsonStr = map.toString()



            aq.ajax(ClientConfig.getHostUrl(ClientConfig.JOSN_CHECK_GRID_NUMBER_PATH),params, String::class.java,  object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200){
                        var response: JSONObject = JSONObject(result)
                        if(response.getInt("status") == 1) {
                            afterDo()
                        }else{
                            noticeMessage(response.getString("msg"))
                        }
                    }else{
                        noticeMessage("网络出问题")
                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            19 -> { reloadIndexShow(currentIndex-1) }
            20 -> { reloadIndexShow(currentIndex+1) }
        }
        return false
    }

    override fun onClick(v: View?) {

        when(v?.id){
            btnPrev.id -> {
                if( currentIndex > 1 )
                     reloadIndexShow(currentIndex-1)
            }
            btnNext.id -> {
                if(currentIndex < Grids.gridNumber) {

                    reloadIndexShow(currentIndex+1)
                }
            }
            btnComplete.id -> {
                BaseActivity.currentScanClass = MultiActivity::class.java.toString()
                finish()
            }
            btnClose.id -> {
                finish()
            }
        }
    }

    override fun afterScanReceive() {
        if(!isCurrentClass()) return

        if(checkLastTime()) {
            if (check() ) {
                var t = Thread(checkGridThread)
                t.start()
            }
        }
    }

    fun afterDo(){
        gridJson.put(currentIndex.toString(),code)

        if(currentIndex < Grids.gridNumber) {
            currentIndex++
        }

        code = ""
        afterSanner()
    }

    fun check():Boolean{
        if( TextUtils.isEmpty(code)){
            return false
        }

        if(code.indexOf("GN-")== -1) {
            noticeMessage("格子号必须以GN- 开头")
            return false
        }

//        var list = ArrayList<Int>()
//        for (key in gridJson.keys()){
//            list.add(parseInt(key))
//            if(parseInt(key) >= currentIndex){
//                break
//            }
//        }
//        list.sort()
//
//
//        for(_key in list){
//            var key = _key.toString()
//            var value = gridJson.getString(key)
//            if(code == value){
//                noticeMessage("格子条码"+value+"已存在于 第"+key+"格")
//                failedNotice()
//                return false
//            }
//        }

        val iterator = gridJson.keys()
        while (iterator.hasNext()) {
            var key = iterator.next()
            if (gridJson.getString(key) == code) {
                noticeMessage( "格子条码" + code + "已存在于 第" + key + "格")
                failedNotice()
                return false
            }
        }


        successNotice()
        return true
    }

    fun afterSanner(){
        Grids.saveGrids()
        txtGrid.text = currentIndex.toString() + "格"
        editText.setText("")
        editText.requestFocus()
        reloadBarcodeResult()
    }

    /**
     *  配货匹配成功提示
     */
    fun successNotice(){
        player.start()
        vibrator.vibrate(800)
    }

    /**
     *  配货匹配失败提示
     */
    fun failedNotice(){
        vibrator.vibrate(300)
    }

    fun reloadBarcodeResult(){
        var result :String = ""
        var i:Int = 1

        var list = ArrayList<Int>()
        for (key in gridJson.keys()){
            list.add(parseInt(key))
        }
        list.sort()

        for(_key in list){
            var key = _key.toString()
            result += key +"格 "+ gridJson.getString(key)
            if(i == currentIndex){
                result += "<---"
            }
            result +="\r\n"
            i++
        }

        var completeCount = 0;
        for (i in i..Grids.gridNumber){
            result += i.toString() + "格 等待扫描"
            if(i == currentIndex){
                result += "<---"
            }
            result +="\r\n"
        }

        val iterator = gridJson.keys()
        while (iterator.hasNext()) {
            if (!TextUtils.isEmpty(gridJson.getString(iterator.next()))) {
                completeCount++
            }
        }

        if(completeCount == gridNumber){
            btnComplete.visibility = View.VISIBLE
            btnNext.visibility = View.INVISIBLE
        }else{
            btnComplete.visibility = View.INVISIBLE
            btnNext.visibility = View.VISIBLE
        }

        txtBarcodeResult.setText(result)
    }

    fun reloadIndexShow(index :Int){
        if(index <= gridNumber && index > 0 ) {
            currentIndex = index
            txtGrid.setText(index.toString())
            reloadBarcodeResult()
            editText.requestFocus()
        }
    }

    fun isLast():Boolean {
        return if(currentIndex == Grids.gridNumber ) true else false
    }

    override fun onBackPressed() {
        BaseActivity.currentScanClass = MultiActivity::class.java.toString()
        super.onBackPressed()
    }


}


